/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

import { ListNode } from '../../helper/ListNode'

/**
 * @param {ListNode} l1
 * @param {ListNode} l2
 * @return {ListNode}
 */
export var addTwoNumbers = function (l1, l2) {
  const [stack1, stack2] = [[], []]
  while (l1 || l2) {
    if (l1) {
      stack1.push(l1.val)
      l1 = l1.next
    }
    if (l2) {
      stack2.push(l2.val)
      l2 = l2.next
    }
  }
  let [ans, carry] = [null, 0]
  while (stack1.length || stack2.length || carry) {
    const sum = (stack1.pop() || 0) + (stack2.pop() || 0) + carry
    carry = sum >= 10 ? 1 : 0
    const node = new ListNode(sum % 10, ans)
    ans = node
  }
  return ans
}
